# !/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@作者 杨阳
@时间 2018-07-31
@说明 与课程相关的实体文件类
@注意事项
"""
import json

from util.JsonUtil import JsonEncoder, classToDict
from util.StrUtil import get_uuid
from util.ThreadPluginsInitUtil import db


class TLessonModel(db.Model):
    """
    与t_lesson表对应的实体类
    """
    __tablename__ = 't_lesson'
    id = db.Column(db.String(36), primary_key=True, index=True, nullable=False, comment='''主键id''')
    code = db.Column(db.String(50), nullable=False, comment='''课程编号''')
    name = db.Column(db.String(200), nullable=False, comment='''课程名称''')
    status = db.Column(db.Integer, nullable=False, comment='''课程发布状态 0:未发布（默认） 1:已发布''')
    allowday = db.Column(db.Integer, nullable=True, comment='''学习天数''')
    mark = db.Column(db.Integer, nullable=True, comment='''通过分数''')
    cost = db.Column(db.Float, nullable=True, comment='''课程费用''')
    hour = db.Column(db.Float, nullable=True, comment='''学时''')
    isopen = db.Column(db.Integer, nullable=False, comment='''是否公开课 0:否1:是（默认）''')
    objectable = db.Column(db.String(500), nullable=True, comment='''使用对象''')
    maker = db.Column(db.Integer, nullable=True, comment='''通过分数''')
    creator = db.Column(db.String(36), nullable=True, comment='''创建人''')
    remark = db.Column(db.String(500), nullable=True, comment='''备注''')
    kj_type = db.Column(db.Integer, nullable=True, comment='''课程类型 2  单一入口课件4  scorm课件 ''')
    create_time = db.Column(db.DateTime, nullable=True, comment='''创建时间''')
    enter_url = db.Column(db.String(500), nullable=True, comment='''单一入口课件的url''')
    training_target = db.Column(db.String(500), nullable=True, comment='''培训目标''')
    training_comment = db.Column(db.String(500), nullable=True, comment='''主要内容''')
    training_manner = db.Column(db.String(500), nullable=True, comment='''培训方式''')
    handbacktime = db.Column(db.Integer, nullable=True, comment='''允许退课时间范围（已废除，退课不做时间限制）''')
    ispermit_preview = db.Column(db.Integer, nullable=True, comment='''是否可以预览 0:不可预览 1:可以预览（默认）''')
    ismini = db.Column(db.Integer, nullable=True, comment='''是否微课件 1:否(默认）2:是''')
    terminaltype = db.Column(db.Integer, nullable=True, comment='''终端类型1:pc终端 2：移动终端 3：pc和移动终端''')
    path = db.Column(db.String(100), nullable=True, comment='''pc终端和移动终端视频名称''')
    coursewareprovider = db.Column(db.String(100), nullable=True, comment='''课件提供商（手动输入）''')
    publishdate = db.Column(db.DateTime, nullable=True, comment='''出版日期''')
    versioncode = db.Column(db.String(20), nullable=True, comment='''课程版本 默认1.0''')
    languagetype = db.Column(db.String(50), nullable=True, comment='''语种 默认：汉语''')
    keyword = db.Column(db.String(500), nullable=True, comment='''课程关键字''')
    author = db.Column(db.String(500), nullable=True, comment='''作者''')
    selfnavigator = db.Column(db.Integer, nullable=True, comment='''控制课件显示类型（三分屏、二分屏）''')
    selfindexlink = db.Column(db.Integer, nullable=True, comment='''课程页面控制参数''')
    teacher = db.Column(db.String(20), nullable=True, comment='''讲师''')
    group_id = db.Column(db.Integer, nullable=True, comment='''所属部门''')
    lesson_img = db.Column(db.String(100), nullable=True, comment='''课程封面图片''')
    urluptype = db.Column(db.Integer, nullable=True, comment='''1 本地路径    0 网络路径''')
    score = db.Column(db.Integer, nullable=True, comment='''学分''')
    resourceids = db.Column(db.String(500), nullable=True, comment='''资源列表''')
    kj_count = db.Column(db.Integer, nullable=True, comment='''mp4小节数量''')
    file = db.Column(db.String(500), nullable=True, comment='''建立课程时上传的文件名''')

    @staticmethod
    def get_entity_byId(id):
        """
        根据id获得实体类对象
        :param   id  实体类id
        """
        entity = TLessonModel.query.filter(TLessonModel.id == id).first()
        return entity

    @staticmethod
    def delete_entity_byId(id):
        """
        根据id删除数据
        :param   id  实体类id
        """
        try:
            entity = TLessonModel.get_entity_byId(id)
            db.session.delete(entity)
            db.session.commit()
            result = {"success": True, "msg": "删除成功!"}
        except Exception as err:
            db.session.rollback()
            result = {"success": True, "msg": "删除失败，请重试!"}
        finally:
            pass
        return json.dumps(result)

    @staticmethod
    def add_entity(code, name, status, allowday, mark, cost, hour, isopen, objectable, maker, creator, remark, kj_type,
                   create_time, enter_url, training_target, training_comment, training_manner, handbacktime,
                   ispermit_preview, ismini, terminaltype, path, coursewareprovider, publishdate, versioncode,
                   languagetype, keyword, author, selfnavigator, selfindexlink, teacher, group_id, lesson_img,
                   urluptype, score, resourceids, kj_count, file):
        """
        增加实体类
        :param           code          课程编号
        :param           name          课程名称
        :param           status          课程发布状态 0:未发布（默认） 1:已发布
        :param           allowday          学习天数
        :param           mark          通过分数
        :param           cost          课程费用
        :param           hour          学时
        :param           isopen          是否公开课 0:否1:是（默认）
        :param           objectable          使用对象
        :param           maker          通过分数
        :param           creator          创建人
        :param           remark          备注
        :param           kj_type          课程类型 2  单一入口课件4  scorm课件
        :param           create_time          创建时间
        :param           enter_url          单一入口课件的url
        :param           training_target          培训目标
        :param           training_comment          主要内容
        :param           training_manner          培训方式
        :param           handbacktime          允许退课时间范围（已废除，退课不做时间限制）
        :param           ispermit_preview          是否可以预览 0:不可预览 1:可以预览（默认）
        :param           ismini          是否微课件 1:否(默认）2:是
        :param           terminaltype          终端类型1:pc终端 2：移动终端 3：pc和移动终端
        :param           path          pc终端和移动终端视频名称
        :param           coursewareprovider          课件提供商（手动输入）
        :param           publishdate          出版日期
        :param           versioncode          课程版本 默认1.0
        :param           languagetype          语种 默认：汉语
        :param           keyword          课程关键字
        :param           author          作者
        :param           selfnavigator          控制课件显示类型（三分屏、二分屏）
        :param           selfindexlink          课程页面控制参数
        :param           teacher          讲师
        :param           group_id          所属部门
        :param           lesson_img          课程封面图片
        :param           urluptype          1 本地路径    0 网络路径
        :param           score          学分
        :param           resourceids          资源列表
        :param           kj_count          mp4小节数量
        :param           file          建立课程时上传的文件名
        """
        try:
            entity = TLessonModel()
            entity.id = get_uuid()
            entity.code = code
            entity.name = name
            entity.status = status
            entity.allowday = allowday
            entity.mark = mark
            entity.cost = cost
            entity.hour = hour
            entity.isopen = isopen
            entity.objectable = objectable
            entity.maker = maker
            entity.creator = creator
            entity.remark = remark
            entity.kj_type = kj_type
            entity.create_time = create_time
            entity.enter_url = enter_url
            entity.training_target = training_target
            entity.training_comment = training_comment
            entity.training_manner = training_manner
            entity.handbacktime = handbacktime
            entity.ispermit_preview = ispermit_preview
            entity.ismini = ismini
            entity.terminaltype = terminaltype
            entity.path = path
            entity.coursewareprovider = coursewareprovider
            entity.publishdate = publishdate
            entity.versioncode = versioncode
            entity.languagetype = languagetype
            entity.keyword = keyword
            entity.author = author
            entity.selfnavigator = selfnavigator
            entity.selfindexlink = selfindexlink
            entity.teacher = teacher
            entity.group_id = group_id
            entity.lesson_img = lesson_img
            entity.urluptype = urluptype
            entity.score = score
            entity.resourceids = resourceids
            entity.kj_count = kj_count
            entity.file = file
            db.session.add(entity)
            db.session.commit()
            result = {"success": True, "msg": "增加成功!"}
        except Exception as err:
            db.session.rollback()
            result = {"success": True, "msg": "增加失败，请重试!"}
        finally:
            pass
        return json.dumps(result)

    @staticmethod
    def update_entity(id, code, name, status, allowday, mark, cost, hour, isopen, objectable, maker, creator, remark,
                      kj_type, create_time, enter_url, training_target, training_comment, training_manner, handbacktime,
                      ispermit_preview, ismini, terminaltype, path, coursewareprovider, publishdate, versioncode,
                      languagetype, keyword, author, selfnavigator, selfindexlink, teacher, group_id, lesson_img,
                      urluptype, score, resourceids, kj_count, file):
        """
        修改数据库
        :param                           id                              课程id
        :param                           code                              课程编号
        :param                           name                              课程名称
        :param                           status                              课程发布状态 0:未发布（默认） 1:已发布
        :param                           allowday                              学习天数
        :param                           mark                              通过分数
        :param                           cost                              课程费用
        :param                           hour                              学时
        :param                           isopen                              是否公开课 0:否1:是（默认）
        :param                           objectable                              使用对象
        :param                           maker                              通过分数
        :param                           remark                              备注
        :param                           kj_type                              课程类型 2  单一入口课件4  scorm课件
        :param                           create_time                              创建时间
        :param                           enter_url                              单一入口课件的url
        :param                           training_target                              培训目标
        :param                           training_comment                              主要内容
        :param                           training_manner                              培训方式
        :param                           handbacktime                              允许退课时间范围（已废除，退课不做时间限制）
        :param                           ispermit_preview                              是否可以预览 0:不可预览 1:可以预览（默认）
        :param                           ismini                              是否微课件 1:否(默认）2:是
        :param                           terminaltype                              终端类型1:pc终端 2：移动终端 3：pc和移动终端
        :param                           path                              pc终端和移动终端视频名称
        :param                           coursewareprovider                              课件提供商（手动输入）
        :param                           publishdate                              出版日期
        :param                           versioncode                              课程版本 默认1.0
        :param                           languagetype                              语种 默认：汉语
        :param                           keyword                              课程关键字
        :param                           author                              作者
        :param                           selfnavigator                              控制课件显示类型（三分屏、二分屏）
        :param                           selfindexlink                              课程页面控制参数
        :param                           teacher                              讲师
        :param                           lesson_img                              课程封面图片
        :param                           urluptype                              1 本地路径    0 网络路径
        :param                           score                              学分
        :param                           resourceids                              资源列表
        :param                           kj_count                              mp4小节数量
        :param                           file                              建立课程时上传的文件名
        """
        try:
            entity = TLessonModel.get_entity_byId(id)
            entity.id = id
            entity.code = code
            entity.name = name
            entity.status = status
            entity.allowday = allowday
            entity.mark = mark
            entity.cost = cost
            entity.hour = hour
            entity.isopen = isopen
            entity.objectable = objectable
            entity.maker = maker
            entity.remark = remark
            entity.kj_type = kj_type
            entity.create_time = create_time
            entity.enter_url = enter_url
            entity.training_target = training_target
            entity.training_comment = training_comment
            entity.training_manner = training_manner
            entity.handbacktime = handbacktime
            entity.ispermit_preview = ispermit_preview
            entity.ismini = ismini
            entity.terminaltype = terminaltype
            entity.path = path
            entity.coursewareprovider = coursewareprovider
            entity.publishdate = publishdate
            entity.versioncode = versioncode
            entity.languagetype = languagetype
            entity.keyword = keyword
            entity.author = author
            entity.selfnavigator = selfnavigator
            entity.selfindexlink = selfindexlink
            entity.teacher = teacher
            entity.lesson_img = lesson_img
            entity.urluptype = urluptype
            entity.score = score
            entity.resourceids = resourceids
            entity.kj_count = kj_count
            entity.file = file
            db.session.commit()
            result = {"success": True, "msg": "修改成功!"}
        except Exception as err:
            db.session.rollback()
            result = {"success": True, "msg": "修改失败，请重试!"}
        finally:
            pass
        return json.dumps(result)

    @staticmethod
    def query_entity_grid(group_id, search_code, search_name, search_status, search_allowday, search_mark, search_cost,
                          search_hour, search_isopen, search_objectable, search_maker, search_remark, search_kj_type,
                          search_create_time, search_enter_url, search_training_target, search_training_comment,
                          search_training_manner, search_handbacktime, search_ispermit_preview, search_ismini,
                          search_terminaltype, search_path, search_coursewareprovider, search_publishdate,
                          search_versioncode, search_languagetype, search_keyword, search_author, search_selfnavigator,
                          search_selfindexlink, search_teacher, search_lesson_img, search_urluptype, search_score,
                          search_resourceids, search_kj_count, search_file, current_page=1):
        """
        查询表格数据
        """
        filters = {1 == 1}
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_code is not None and search_code != '':
            filters.add(TLessonModel.code == search_code)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_name is not None and search_name != '':
            filters.add(TLessonModel.name == search_name)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_status is not None and search_status != '':
            filters.add(TLessonModel.status == search_status)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_allowday is not None and search_allowday != '':
            filters.add(TLessonModel.allowday == search_allowday)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_mark is not None and search_mark != '':
            filters.add(TLessonModel.mark == search_mark)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_cost is not None and search_cost != '':
            filters.add(TLessonModel.cost == search_cost)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_hour is not None and search_hour != '':
            filters.add(TLessonModel.hour == search_hour)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_isopen is not None and search_isopen != '':
            filters.add(TLessonModel.isopen == search_isopen)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_objectable is not None and search_objectable != '':
            filters.add(TLessonModel.objectable == search_objectable)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_maker is not None and search_maker != '':
            filters.add(TLessonModel.maker == search_maker)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_remark is not None and search_remark != '':
            filters.add(TLessonModel.remark == search_remark)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_kj_type is not None and search_kj_type != '':
            filters.add(TLessonModel.kj_type == search_kj_type)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_create_time is not None and search_create_time != '':
            filters.add(TLessonModel.create_time == search_create_time)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_enter_url is not None and search_enter_url != '':
            filters.add(TLessonModel.enter_url == search_enter_url)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_training_target is not None and search_training_target != '':
            filters.add(TLessonModel.training_target == search_training_target)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_training_comment is not None and search_training_comment != '':
            filters.add(TLessonModel.training_comment == search_training_comment)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_training_manner is not None and search_training_manner != '':
            filters.add(TLessonModel.training_manner == search_training_manner)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_handbacktime is not None and search_handbacktime != '':
            filters.add(TLessonModel.handbacktime == search_handbacktime)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_ispermit_preview is not None and search_ispermit_preview != '':
            filters.add(TLessonModel.ispermit_preview == search_ispermit_preview)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_ismini is not None and search_ismini != '':
            filters.add(TLessonModel.ismini == search_ismini)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_terminaltype is not None and search_terminaltype != '':
            filters.add(TLessonModel.terminaltype == search_terminaltype)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_path is not None and search_path != '':
            filters.add(TLessonModel.path == search_path)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_coursewareprovider is not None and search_coursewareprovider != '':
            filters.add(TLessonModel.coursewareprovider == search_coursewareprovider)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_publishdate is not None and search_publishdate != '':
            filters.add(TLessonModel.publishdate == search_publishdate)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_versioncode is not None and search_versioncode != '':
            filters.add(TLessonModel.versioncode == search_versioncode)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_languagetype is not None and search_languagetype != '':
            filters.add(TLessonModel.languagetype == search_languagetype)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_keyword is not None and search_keyword != '':
            filters.add(TLessonModel.keyword == search_keyword)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_author is not None and search_author != '':
            filters.add(TLessonModel.author == search_author)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_selfnavigator is not None and search_selfnavigator != '':
            filters.add(TLessonModel.selfnavigator == search_selfnavigator)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_selfindexlink is not None and search_selfindexlink != '':
            filters.add(TLessonModel.selfindexlink == search_selfindexlink)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_teacher is not None and search_teacher != '':
            filters.add(TLessonModel.teacher == search_teacher)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_lesson_img is not None and search_lesson_img != '':
            filters.add(TLessonModel.lesson_img == search_lesson_img)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_urluptype is not None and search_urluptype != '':
            filters.add(TLessonModel.urluptype == search_urluptype)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_score is not None and search_score != '':
            filters.add(TLessonModel.score == search_score)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_resourceids is not None and search_resourceids != '':
            filters.add(TLessonModel.resourceids == search_resourceids)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_kj_count is not None and search_kj_count != '':
            filters.add(TLessonModel.kj_count == search_kj_count)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        if search_file is not None and search_file != '':
            filters.add(TLessonModel.file == search_file)
        if group_id is not None and group_id != '':
            filters.add(TLessonModel.group_id == group_id)
        # 查询数据集合
        entity_list = TLessonModel.query.filter(*filters).order_by(TLessonModel.create_time.desc()).limit(10).offset(
            (int(current_page) - 1) * 10)
        # 查询总记录数
        total = db.session.query(TLessonModel.id).filter(*filters).count()
        list = []
        for obj in entity_list:
            list.append(classToDict(obj))
        retu = {"success": True, "grid": list, "total_count": total}
        result = json.dumps(retu, cls=JsonEncoder)
        return result
